package client

import (
	transport "goproject/socket"
	"log"
	"net"
)

func connect2TcpServer(serverAddr string) *net.TCPConn {
	tcpAddr, err := net.ResolveTCPAddr("tcp4", serverAddr)
	transport.CheckError(err)
	conn, err := net.DialTCP("tcp4", nil, tcpAddr)
	transport.CheckError(err)
	log.Printf("establish connection to server %s myself %s\n", conn.RemoteAddr().String(), conn.LocalAddr().String())
	return conn
}

func sendTcpServer(conn net.Conn) {
	n, err := conn.Write(append([]byte("hello"), transport.MAGIC...))
	transport.CheckError(err)
	log.Printf("send %d bytes\n", n)
}

func TcpClient() {
	conn := connect2TcpServer("127.0.0.1:5678")
	sendTcpServer(conn)
	conn.Close()
	log.Println("close connection")
}

func TcpStick() {
	conn := connect2TcpServer("127.0.0.1:5678")

	for i := 0; i < 3; i++ {
		sendTcpServer(conn)
	}
	conn.Close()
	log.Println("close connection")
}
